<template>
    <view class="page bgf8" :style="{'--color': color}">
        <status-bar title='提交订单'></status-bar>
        <view class="padding20">
            <view class="card">
                <view class="size32 black bold">桌号：{{ pageData.data[0].table_code_name || '' }}</view>
            </view>
        </view>
        <view class="p-left20 p-right20">
            <view class="card">
                <view class="goodsList" :class="{'m-top30': index}" v-for="(item,index) in pageData.data" :key="index">
                    <view class="size30 black bold p-bot10">{{ item.shopName }}</view>
                    <view class="d-flex m-top20" v-for="(itm,idx) in item.list" :key="idx">
                        <image class="thumb bor_radius_4" :src="$imgUrls(itm.img)" mode="aspectFill"></image>
                        <view class="flex-1 d-flex f-column j-sb p-left20">
                            <view class="size28 color_33 ellipsis">{{itm.name}}</view>
                            <view class="h7 color_99 ellipsis">{{itm.operation_text}}</view>
                            <view class="d-flex j-sb a-center">
                                <view class="color_E9">
                                    <text class="h7">￥</text>
                                    <text class="size28">{{itm.price}}</text>
                                </view>
                                <view class="d-flex a-center">
                                    <text class="iconfont icon-jianshao1 size36" @click="delBtn(itm)"></text>
                                    <view class="amount h6 color_33 text-center">{{itm.num}}</view>
                                    <text class="iconfont icon-zengjia size36" @click="addBtn(itm)"></text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="d-flex j-sb a-center m-top40" v-if="couponData">
                    <view class="size28 m-right20">优惠券</view>
                    <view v-if="couponID && integralData" class="d-flex a-center" @click="preferential(1)">
                        <text class="size32 color_E9 m-right10">-￥{{integralData.disMoney}}</text>
                        <text class="iconfont icon-xiangyouxiayiye h6 color_99"></text>
                    </view>
                    <view v-else class="coupon flexac" @click="preferential(1)">
                        <text class="white m-right10">待使用</text>
                        <text class="iconfont icon-xiangyouxiayiye h6 white"></text>
                    </view>
                </view>
                <view class="d-flex j-sb a-center m-top40" v-if="integralData.exchangeFen > 0">
                    <view class="size28 m-right20">积分</view>
                    <view class="d-flex a-center" @click="preferential(0)">
                        <view class="fake-radio" :class="useIntegral == 1 ? 'thmeBorder thmeBg' : ''">
                            <text class="iconfont icon-xuanzhong white"></text>
                        </view>
                        <view class="color_66">用<text class="size26 c_ff4400">{{ integralData.exchangeFen }}</text>积分抵扣
                            <text class="size26 c_ff4400">{{ parseFloat(integralData.genToMoney).toFixed(2) }}</text>元</view>
                    </view>
                </view>
                <view class="d-flex j-end a-center p-top60 bold">
                    <view class="size26">已优惠</view>
                    <view class="size32 color_E9">-￥{{ integralData.allDiscount || '0.0' }}</view>
                    <view class="size26 m-left20 m-right20">共{{ pageData.allGoodsNumber || '' }}件</view>
                    <view class="size26">合计</view>
                    <view class="size26 color_E9">￥</view>
                    <view class="size42 color_E9">{{paymentMoney == 0 ? '0.00' : parseFloat(paymentMoney).toFixed(2)}}</view>
                </view>
            </view>
        </view>
        <view class="padding20">
            <view class="card d-flex j-sb a-center">
                <view class="size28 m-right20">备注</view>
                <input v-model="remark" placeholder="选填，给商家留言" class="flex-1 text-right">
            </view>
        </view>
        <view class="footer_info">
            <view class="ftr_info_price">
                实付：<view class="price5 size48">￥{{paymentMoney == 0 ? '0.00' : parseFloat(paymentMoney).toFixed(2)}}</view>
            </view>
            <view class="btn flexac size32 white" @click="handlePay">{{ order_id == 0 ? '立即支付' : '确认添加' }}</view>
        </view>

        <!-- 选择优惠券 -->
        <couponCheck :list="couponData" v-if="showCouponPop" @close="showCouponPop = false"
            :couponID="couponID" @change="_couponClick"></couponCheck>

        <showModel type="99" v-if="showModal" title="是否确认支付" msg="支付成功后可在我的订单中查看" btn2="去支付" 
            btn4="稍后支付" @certain="paySure" @cancelFunc="showModal = false" @otherFunc="payLater"></showModel>

        <showModel type="99" v-if="showModal2" title="提示" msg="当前商品已清空" btn2="返回" 
            @certain="toUrl('/otherPage/custom/placeOrder?tid='+tid)"></showModel>
    </view>
</template>

<script>
import { mapState } from 'vuex'
import couponCheck from '../components/couponCheck.vue'
export default {
    data(){
        return {
            tid: '',
            car_id: '',
            order_id: '', // 有值：未付订单加餐
            pageData: '',
            paymentMoney: 0, // 实付款
            couponData: '',
            integralData: '',
            remark: '',
            showCouponPop: false,
            couponID: '',
            useIntegral: 0, // 1代表使用积分
            showModal: false, // 确认支付
            showModal2: false,
            flagPay: true, // 避免多次提交订单
            pay_mode: 1, // 1为拼桌(独立)、2为同桌(合并)
            timer: null,
            userData: ''
        }
    },
    computed: {
        ...mapState(['color', 'vid']),
    },
    components: {
        couponCheck
    },
    onLoad(e){
        if(e.tid) this.tid = e.tid
        if(e.car_id) this.car_id = e.car_id
        if(e.order_id) this.order_id = e.order_id
        if(e.pay_mode) this.pay_mode = e.pay_mode
    },
    onShow(){
        this.getPurchase()
        this.getCoupon()
        this._getPreferential()
        this.getOldAddress()
        
        if(this.pay_mode == 2 && !this.timer){
            console.log('开启2')
            this.timer = setInterval(()=>{
                this.getPurchase()
                this._getPreferential()
            }, 3000)
        }
    },
    onHide(){
        if(this.timer){
            clearInterval(this.timer)
            this.timer = null
            console.log('关闭timer')
        }
        setTimeout(()=>{
            if(this.timer){
                clearInterval(this.timer)
                this.timer = null
            }
        },3000)
    },
    onUnload(){
        console.log('页面卸载')
        if(this.timer){
            clearInterval(this.timer)
            this.timer = null
            console.log('关闭timer')
        }
        setTimeout(()=>{
            if(this.timer){
                clearInterval(this.timer)
                this.timer = null
            }
        },3000)
    },
    methods: {
        getPurchase(){
            this.$http.post({
                url: '/zzj_singleSaleApi/getPurchase',
                data: {
                    car_id: this.car_id,
                    tid: this.tid
                }
            }).then(res=>{
                if(res.operate == 'endOrder'){
                    this.showModal2 = true
                    this.car_id = ''
                    return
                }
                this.showModal2 = false
                if(res.operate == 'refreshOrder'){
                    this.car_id = res.data || ''
                    // if(!this.car_id) return this.$back()
                    if(!this.car_id) return
                    this.getPurchase()
                    return
                }
                this.pageData = res
                if(this.couponID || this.useIntegral == 1) return
                this.paymentMoney = res.all_payment
            })
        },
        getCoupon(){
            this.$http.post({ // 非购物车下单则要传goods_id和num
                url: '/SRA_simMallApi/getCoupons2',
                data: {
                    vId: this.vid,
                    operation_id: 0,
                    carIds: this.car_id
                }
            }).then(res=>{
                if(res.code == 100 && res.data){
                    this.couponData = res.data
                }
            })
        },
        preferential(num){
            if(num == 1){ // 使用优惠券
                this.showCouponPop = true
            } else{ // 使用积分
                this.useIntegral = this.useIntegral == 1 ? 0 : 1
                this._getPreferential()
            }
        },
        getOldAddress(){
            this.$http.post({
                url: '/SRA_simMallApi/getOldAddress',
                data: {
                    type: 3
                }
            }).then(res=>{
                this.userData = res.data.userFind
            })
        },
        _couponClick(couponId){
            this.couponID = couponId
            this._getPreferential()
            this.showCouponPop = false
        },
        _getPreferential(){
            let apiUrl, params = { // 无运费不传express
                vId: this.vid,
                couponsId: this.couponID,
                useIntegral: this.useIntegral
            }
            if(this.car_id){ // 购物车下单
                apiUrl = '/SRA_simMallApi/getPreferential2'
                params.carIds = this.car_id
                params.operationId = ''
            }
            if(!apiUrl) return
            this.$http.get({
                url: apiUrl,
                data: params
            }).then(res=>{
                if(res.code == 100 && res.data){
                    this.integralData = res.data
                    this.paymentMoney = res.data.payMoney
                }
            })
        },
        createOrder(){ // 立即或稍后支付都要生成订单
            return new Promise(resolve=>{
                let share_v_id = uni.getStorageSync("share_v_id")
                if(this.flagPay){
                    this.flagPay = false
                    let apiUrl, params = {
                        delivery: 2, // 自提
                        uname: this.userData.v_name,
                        utel: this.userData.v_tel,
                        totalMoney: this.paymentMoney,
                        remarks: this.remark,
                        couponID: this.couponID,
                        useIntegral: this.useIntegral,
                        aes_coupon: this.integralData.aes_coupon || '',
                        share_v_id,
                        shop_id: this.pageData.data[0].shop_id,
                        tid: this.tid
                    }
                    if(this.car_id){ // 购物车下单
                        apiUrl = '/zzj_singleSaleApi/storePayCart'
                        params.couponsId = this.couponID
                        params.car_id = this.car_id
                    }
                    if(!apiUrl) return
                    this.$showLoading('下单中...')
                    this.$http.post({
                        url: apiUrl,
                        data: params
                    }).then(res=>{
                        resolve(res)
                    })
                }
            })
        },
        confirmOrder(union_order_code){ // 添加商品、选稍后支付、取消支付需确认订单
            return new Promise(resolve=>{
                this.$http.post({
                    url: '/singleSaleApi/tableConfirmOrder',
                    data: {
                        order_id: this.order_id, // 为0时必传union_order_code
                        union_order_code,
                        car_id: this.car_id,
                        tid: this.tid
                    }
                }).then(res=>{
                    resolve(res)
                })
            })
        },
        handlePay(){
            console.log(this.order_id)
            if(this.order_id == 0) return this.showModal = true

            this.$http.post({ // 给未支付订单添加商品
                url: '/singleSaleApi/addGoodsToOrder',
                data: {
                    order_id: this.order_id,
                    car_id: this.car_id,
                    tid: this.tid
                }
            }).then(async res=>{
                await this.confirmOrder('')
                this.toUrl('/otherPage/custom/viewOrder?order_id=' + this.order_id + '&tid=' + this.tid)
            })
        },
        async payLater(){
            let res = await this.createOrder()
            if(res.code == 100 && res.payID){
                await this.confirmOrder(res.union_order_code)
                this.toUrl('/otherPage/custom/placeOrder?tid=' + this.tid)
                return
            }
            this.$Toast(res.msg)
            this.flagPay = true
            uni.hideLoading()
        },
        async paySure(){
            let res = await this.createOrder()
            if(res.code == 100 && res.payID){
                // #ifdef H5
                window.location.href ='https://sra.mogoie.com/index.php/accountPay/weChatCashierPage?orderStr=' + res.payID
                // #endif
                // #ifndef H5
                this.toUrl('/moneyPage/capital/checkstand?payid='+res.payID+'&path=1&tid='+this.tid+'&union_order_code='+res.union_order_code+'&car_id='+this.car_id)
                // #endif
                return
            }
            this.$Toast(res.msg)
            this.flagPay = true
            uni.hideLoading()
        },
        addBtn(item){
            this.incCart(item.car_id, parseInt(item.num) + 1)
        },
        delBtn(item){
            console.log(item)
            if(item.num > 1){
                this.incCart(item.car_id, parseInt(item.num) - 1) 
                return 
            }
            this.delCart(item.car_id)
        },
        incCart(car_id, num){ // 改变某商品加购数量
            this.$http.post({
                url: '/zzj_singleSaleApi/incCart',
                data: {
                    car_id,
                    num,
                    tid: this.tid
                }
            }).then(res=>{
                if(res.errcode != 100) return this.$Toast(res.msg)
                this.getPurchase()
                this._getPreferential()
            })
        },
        delCart(car_id){ // 某商品移出购物车
            this.$Modal('提示','确定不要了吗？').then(res=>{
                if(!res) return
                this.$http.post({
                    url: '/zzj_singleSaleApi/delCart',
                    data: {
                        car_id,
                        tid: this.tid
                    }
                }).then(res=>{
                    if(res.errcode != 100) return this.$Toast(res.msg)
                    let ids = this.car_id.split(',')
                    let i = ids.findIndex(n => n == car_id)
                    ids.splice(i, 1)
                    this.car_id = ids.join()
                    this.getPurchase()
                    this._getPreferential()
                    if(!this.car_id) this.$back()
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.page {
    padding-bottom: calc(130rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(130rpx + env(safe-area-inset-bottom));
}
.card {
    box-shadow: 0 2px 4px rgba(0,0,0,.06);
    border-radius: 20rpx;
    background: #fff;
    padding: 30rpx;
}
.goodsList {
    .thumb {
        width: 120rpx;
        height: 120rpx;
        border: 1px solid #ddd;
    }
    .amount {
        width: 60rpx;
    }
    .icon-jianshao1, .icon-zengjia {
        color: var(--color);
    }
}
.coupon {
    height: 40rpx;
    padding: 0 20rpx;
    background: #fe704c;
    border-radius: 20rpx;
}
.footer_info {
    padding-top: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    .btn {
        width: 200rpx;
        height: 98rpx;
        background: var(--color);
    }
}
</style>